package com.yzqp.common.mvc.httpmessage;

import com.alibaba.fastjson.parser.DefaultJSONParser;
import com.alibaba.fastjson.parser.JSONLexer;
import com.alibaba.fastjson.parser.JSONToken;
import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer;
import com.alibaba.fastjson.serializer.JSONSerializer;
import com.alibaba.fastjson.serializer.ObjectSerializer;

import java.lang.reflect.Type;

/**
 * springmvc fastJson  boolean的序列化和反序列化的
 */
public class BooleanFastJsonHttpMessageConverter implements ObjectSerializer, ObjectDeserializer {
    /**
     * fastjson 序列化
     *
     * @param serializer
     * @param object
     * @param fieldName
     * @param fieldType
     * @param features
     */
    @Override
    public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) {
        //枚举为空
        if (object == null) {
            serializer.writeNull();
        }
        //系列化大写的值
        serializer.write((Boolean) object + "");
        String valueName = null;
        if ((Boolean) object) {
            valueName = "是";
        } else {
            valueName = "否";
        }
        //serializer.writeWithFieldName(name, fieldName.toString() + "Name");
        //serializer.writeWithFieldName(name, fieldName.toString() + "Name", String.class, features + 1);
        serializer.getWriter().write(", \n\"" + fieldName + "Name\":  \"" + valueName + "\"");
    }

    @Override
    public int getFastMatchToken() {
        return JSONToken.LITERAL_STRING;
    }

    /**
     * fastjson 反序列化
     *
     * @param parser
     * @param type
     * @param fieldName
     * @return
     */
    @Override
    @SuppressWarnings("unchecked")
    public Boolean deserialze(DefaultJSONParser parser, Type type, Object fieldName) {

        final JSONLexer lexer = parser.lexer;
        final int token = lexer.token();
        Boolean value = null;
        if (token == JSONToken.LITERAL_INT) {
            Number valueNumber = lexer.integerValue();
            if (valueNumber.intValue() == 0) {
                value = false;
            } else {
                value = true;
            }
        } else if (token == JSONToken.LITERAL_STRING) {
            String valueString = lexer.stringVal();
            value = Boolean.parseBoolean(valueString);
        } else if (token != JSONToken.NULL) {
            value = null;
        }
        return value;
    }
}
